package com.example.costumview.customview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

public class ContainView extends View {

    private Paint mPaint;
    private Rect mRect;
    private int mX;
    private int mY;

    public ContainView(Context context) {
        super(context);
        init();
    }

    public ContainView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ContainView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mPaint = new Paint();
        mPaint.setColor(Color.GREEN);
        mPaint.setStyle(Paint.Style.FILL);
        mRect = new Rect(100, 100, 600, 400);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.drawRect(mRect, mPaint);
        if (mRect.contains(mX,mY)){
            mPaint.setColor(Color.RED);
        }else{
            mPaint.setColor(Color.GREEN);
        }
        canvas.drawRect(mRect,mPaint);

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mX = (int) event.getX();
        mY = (int) event.getY();

        if (event.getAction()==MotionEvent.ACTION_DOWN){
            invalidate();
            return true;//返回true，表示当前控件已经拦截这个消息了，所以后续的ACTION_MOVE和ACTION_UP都会继续传进来。
        }else if (event.getAction()==MotionEvent.ACTION_UP){
            mX=-1;
            mY=-1;
        }
        postInvalidate();
        return super.onTouchEvent(event);
    }
}
